package org.ljy.forum6.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.ljy.forum6.common.AppConfig;
import org.ljy.forum6.common.AppResult;
import org.ljy.forum6.common.ResultCode;
import org.ljy.forum6.exception.ApplicationException;
import org.ljy.forum6.model.Message;
import org.ljy.forum6.model.User;
import org.ljy.forum6.services.IMessageService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接受者Id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("私信内容") @RequestParam("content") @NonNull String content) {
        //1.获取发送者对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2.判断发送者
        log.info(String.valueOf(user.getState()));
        if(user.getState() == 1) {
            log.warn("用户已被禁言，无法发送私信");
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if(user.getId() == receiveUserId) {
            log.warn("不能给自己发送私信");
            return AppResult.failed("无法给自己发送私信");
        }
        //3.判断接受者


        //4.封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        //5.调用service
        messageService.create(message);
        //6.返回结果
        return  AppResult.success();
    }

    /**
     * 获取未读站内信个数
     * @param request 获取登陆用户的id
     * @return
     */
    @ApiOperation("获取未读站内信个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //1.获取登陆用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null ) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //2.调用service
        Integer count = messageService.selectUnreadCount(user.getId());
        //3.
        return AppResult.success(count);
    }

    @ApiOperation("获取站内信列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        //1.获取登陆用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        if(messages == null) {
            messages = new ArrayList<>();
        }
        return AppResult.success(messages);
    }

    @ApiOperation("读取站内信")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @RequestParam("id") @NonNull Long id) {
        //1.查询该站内信是否存在
        Message message = messageService.selectById(id);
        if(message == null || message.getDeleteState() == 1) {
            log.warn("站内信不存在");
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.验证登陆用户和站内信是否同一个人
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getId() != message.getReceiveUserId()) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //3.调用service
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("回复的站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("回复内容") @RequestParam("content") @NonNull String content) {
        //1.查询出待回复站内信对象
        Message exitMessage = messageService.selectById(repliedId);
        if(exitMessage == null || exitMessage.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.获取登陆用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null || user.getState() == 1 ) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }
        if(user.getId() == exitMessage.getPostUserId()) {
            log.warn("不能给自己回复");
            return AppResult.failed("不能给自己回复");
        }
        //3.构造更新对象
        Message updateMessage = new Message();
        updateMessage.setPostUserId(user.getId());
        updateMessage.setReceiveUserId(repliedId);
        updateMessage.setContent(content);
        Date date = new Date();
        updateMessage.setCreateTime(date);
        updateMessage.setUpdateTime(date);
        //4.调用service
        messageService.reply(repliedId, updateMessage);
        return AppResult.success();
    }


}
